# -*- coding : utf_8 -*-
'''
=======================================
Time : 2025/3/20 22:36
Author : 田霄汉
Email : 522989570@qq.com
File : oracle_util.py
Project : pytest_demo
=======================================
'''

import cx_Oracle as oracle

class OracleUtil:

    def __init__(self):

        self.host = ""
        self.port = ""
        self.sid = ""
        self.user = ""
        self.password = ""

    def connecion_oracle(self):
        """
        连接oracle数据库
        :return: connection, cursor
        """
        try:
            dsn = oracle.makedsn(host=self.host, port=self.port, sid=self.sid)
            connection = dsn.connect(user=self.user, password=self.password, dsn=dsn)
            cursor = connection.cursor()
            return connection, cursor
        except ConnectionError:
            print("===连接Oracle数据库异常，请检查连接信息")

    def close_oracle(self, connection, cursor):
        """
        关闭Oracle数据库连接
        :param connection: Oracle连接
        :param cursor: Oracle游标
        :return:
        """
        try:
            cursor.close()
            connection.close()
        except IOError:
            print("===关闭Oracle数据库连接失败，请检查数据库状态===")

    def get_select_oracle(self, sql):
        """
        获取Oracle查询结果
        :param sql: Oracle查询语句
        :return: result查询结果
        """
        connection, cursor =self.connecion_oracle()
        try:
            if ";" in sql:
                sql.replace(";", "")
            elif "；" in sql:
                sql.replace("；", "")
            select_result = cursor.excute(sql)
            result = select_result.fetchall()
            return result
        except Exception:
            print("===执行Oracle查询语句报错===")
        finally:
            self.close_oracle(connection=connection, cursor=cursor)

    def exc_update_oracle(self, sql):
        """
        执行Oracle变更
        :param sql: Oracle变更语句
        :return: result变更结果
        """
        connection, cursor = self.connecion_oracle()
        try:
            if ";" in sql:
                sql.replace(";", "")
            elif "；" in sql:
                sql.replace("；", "")
            cursor.excute(sql)
            connection.commit()
        except Exception:
            connection.rollback()
            print("===执行修改语句Oracle报错，数据已经回滚===")
        finally:
            self.close_oracle(connection=connection, cursor=cursor)